﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using KMF.DAL;
using KMF.Utility;
using KMF.WebUI.Attributes;
using KMF.WebUI.CustomHelpers;
using KMF.WebUI.Infrastructure;
using KMF.WebUI.Models;

namespace ECG.WebUI.Controllers
{

    public class OrderController : Controller
    {
        //
        // GET: /Order/

        [CheckSessionCart]
        public ActionResult Index()
        {
            if (Session[SessionConfig.SessionCustomerLogin] != null)
            {
                return RedirectToAction("Finish", "Order");
            }
            return View();
        }

        [CheckSessionCart]
        [HttpPost]
        public ActionResult Index(CustomerLoginModel model)
        {
            var hasEmail = CustomerDb.GetByEmail(model.Email);
            if (hasEmail != null)
            {
                //ModelState.AddModelError("error", "Không tồn tại email này!");
                var customerInfoLogin = new CustomerInfo
                {
                    Address = hasEmail.Address,
                    BirthDay = hasEmail.Birthday,
                    CustomerId = hasEmail.Id,
                    DistrictId = hasEmail.DistrictId.ToString(),
                    DistrictName = hasEmail.DistrictName,
                    Email = hasEmail.Email,
                    FullName = hasEmail.FullName,
                    Gender = hasEmail.Gender,
                    MobilePhone = hasEmail.Mobilephone,
                    ProvinceId = hasEmail.ProvinceId.ToString(),
                    ProvinceName = hasEmail.ProvinceName,
                    Telephone = hasEmail.Telephone
                };
                Session[SessionConfig.SessionCustomerLogin] = customerInfoLogin;

                if (Session[SessionConfig.SessionCustomerLogin] != null)
                {
                    var orderInfo = (OrderInfo)Session[SessionConfig.SessionCartInfor];
                    orderInfo.CustomerId = customerInfoLogin.CustomerId;
                    orderInfo.FullName = customerInfoLogin.FullName;
                    orderInfo.Email = customerInfoLogin.Email;
                    orderInfo.Telephone = customerInfoLogin.Telephone;
                    orderInfo.MobilePhone = customerInfoLogin.MobilePhone;
                    orderInfo.Address = customerInfoLogin.Address;
                    orderInfo.DistrictId = customerInfoLogin.DistrictId;
                    orderInfo.DistrictName = customerInfoLogin.DistrictName;
                    orderInfo.ProvinceId = customerInfoLogin.ProvinceId;
                    orderInfo.ProvinceName = customerInfoLogin.ProvinceName;
                    orderInfo.Gender = customerInfoLogin.Gender;
                }
            }
            if (ModelState.IsValid)
            {
                return RedirectToAction("Finish", "Order");
            }
            return View(model);
        }

        [CheckSessionCart]
        public ActionResult Finish()
        {
            var model = new RegisterInOrderModel();
            var provinceList = FunctionHelpers.GetProvinceList();
            provinceList.Insert(0, new ProvinceModel { ProvinceId = "", ProvinceName = "- Lựa chọn -" });
            var districtList = new List<DistrictModel>();
            districtList.Insert(0, new DistrictModel { DistrictId = "", DistrictName = "- Lựa chọn -" });

            model.ProvinceList = provinceList;
            model.DistrictList = districtList;
            model.ProvinceListAdd = provinceList;
            model.DistrictListAdd = districtList;

            var yearList = new List<YearModel>();
            for (var i = 1940; i <= 2013; i++)
            {
                yearList.Add(new YearModel { YearVal = i.ToString(), Year = i.ToString() });
            }
            yearList.Insert(0, new YearModel { YearVal = "", Year = "Năm" });
            model.YearList = yearList;

            var monthList = new List<MonthModel>();
            for (var i = 1; i <= 12; i++)
            {
                monthList.Add(new MonthModel { MonthVal = i.ToString(), Month = i.ToString() });
            }
            monthList.Insert(0, new MonthModel { MonthVal = "", Month = "Tháng" });
            model.MonthList = monthList;

            var dayList = new List<DayModel>();
            dayList.Insert(0, new DayModel { DayVal = "", Day = "Ngày" });
            model.DayList = dayList;

            model.IsAddressDiff = true;

            return View(model);
        }

        [CheckSessionCart]
        [HttpPost]
        public ActionResult Finish(RegisterInOrderModel model, string comment, string payment)
        {
            var error = false;
            if (!model.IsAddressDiff)
            {
                if (string.IsNullOrEmpty(model.FullNameAddition))
                {
                    ModelState.AddModelError("ErrorFullNameAdd", "Bạn cần nhập họ tên!");
                    error = true;
                }
                if (string.IsNullOrEmpty(model.PhoneAddition))
                {
                    ModelState.AddModelError("ErrorPhoneAdd", "Bạn cần nhập số điện thoại!");
                    error = true;
                }
                if (string.IsNullOrEmpty(model.AddressAddition))
                {
                    ModelState.AddModelError("ErrorAddressAdd", "Bạn cần nhập địa chỉ!");
                    error = true;
                }
                if (string.IsNullOrEmpty(model.ProvinceIdAdd))
                {
                    ModelState.AddModelError("ErrorProvinceAdd", "Chọn tỉnh thành!");
                    error = true;
                }
                if (string.IsNullOrEmpty(model.DistrictIdAdd))
                {
                    ModelState.AddModelError("ErrorDistrictAdd", "Chọn quận huyện!");
                    error = true;
                }
            }

            // Check email exists
            //if(!string.IsNullOrEmpty(model.Email))
            //{
            //    var hasEmail = CustomerDb.GetByEmail(model.Email);
            //    if(hasEmail != null)
            //    {
            //        ModelState.AddModelError("ErrorHasEmail", "Địa chỉ Email này đã được sử dụng - ");
            //    }
            //}


            if (Session[SessionConfig.SessionCustomerLogin] == null)
            {
                if (ModelState.IsValid)
                {
                    // Insert register and send mail
                    // kiem tra email xem co chua neu chua thi them email nay vao
                    var hasEmail = CustomerDb.GetByEmail(model.Email);
                    if (hasEmail == null)
                    {
                        FunctionHelpers.InsertCustomerRegister(model);
                    }

                    // Insert order and send mail
                    var orderInfo = (OrderInfo)Session[SessionConfig.SessionCartInfor];
                    FunctionHelpers.InsertOrder(orderInfo, model, payment, comment);
                    return RedirectToAction("OrderInformation", "Order");
                }
            }
            else if (!error)
            {
                var customerInfo = (CustomerInfo)Session[SessionConfig.SessionCustomerLogin];
                var objPost = new RegisterInOrderModel
                {
                    Email = customerInfo.Email,
                    FullName = customerInfo.FullName,
                    Telephone = customerInfo.Telephone,
                    MobilePhone = customerInfo.MobilePhone,
                    Address = customerInfo.Address,
                    ProvinceId = customerInfo.ProvinceId,
                    ProvinceName = customerInfo.ProvinceName,
                    DistrictId = customerInfo.DistrictId,
                    DistrictName = customerInfo.DistrictName,
                    Gender = customerInfo.Gender,
                    IsAddressDiff = model.IsAddressDiff,
                    FullNameAddition = model.FullNameAddition,
                    PhoneAddition = model.PhoneAddition,
                    AddressAddition = model.AddressAddition,
                    ProvinceIdAdd = model.ProvinceIdAdd,
                    ProvinceNameAdd = model.ProvinceNameAdd,
                    DistrictIdAdd = model.DistrictIdAdd,
                    DistrictNameAdd = model.DistrictNameAdd
                };
                // Insert order and send mail
                var orderInfo = (OrderInfo)Session[SessionConfig.SessionCartInfor];
                FunctionHelpers.InsertOrder(orderInfo, objPost, payment, comment);
                return RedirectToAction("OrderInformation", "Order");
            }

            // Error
            var provinceList = FunctionHelpers.GetProvinceList();
            provinceList.Insert(0, new ProvinceModel { ProvinceId = "", ProvinceName = "- Lựa chọn -" });
            var districtList = FunctionHelpers.GetDistrictList(int.Parse(string.IsNullOrEmpty(model.ProvinceId) ? "-1" : model.ProvinceId)) ?? new List<DistrictModel>();
            districtList.Insert(0, new DistrictModel { DistrictId = "", DistrictName = "- Lựa chọn -" });

            var districtListAdd = FunctionHelpers.GetDistrictList(int.Parse(string.IsNullOrEmpty(model.ProvinceIdAdd) ? "-1" : model.ProvinceIdAdd)) ?? new List<DistrictModel>();
            districtListAdd.Insert(0, new DistrictModel { DistrictId = "", DistrictName = "- Lựa chọn -" });

            model.ProvinceList = provinceList;
            model.DistrictList = districtList;
            model.ProvinceListAdd = provinceList;
            model.DistrictListAdd = districtListAdd;

            var yearList = new List<YearModel>();
            for (var i = 1940; i <= 2013; i++)
            {
                yearList.Add(new YearModel { YearVal = i.ToString(), Year = i.ToString() });
            }
            yearList.Insert(0, new YearModel { YearVal = "", Year = "Năm" });
            model.YearList = yearList;

            var monthList = new List<MonthModel>();
            for (var i = 1; i <= 12; i++)
            {
                monthList.Add(new MonthModel { MonthVal = i.ToString(), Month = i.ToString() });
            }
            monthList.Insert(0, new MonthModel { MonthVal = "", Month = "Tháng" });
            model.MonthList = monthList;

            var dayList = new List<DayModel>();
            dayList.Insert(0, new DayModel { DayVal = "", Day = "Ngày" });
            model.DayList = dayList;
            return View(model);
        }

        [CheckSessionCart]
        public ActionResult DeleteProductInCart(string productId)
        {
            var cartInfo = (OrderInfo)Session[SessionConfig.SessionCartInfor];
            var pItem = cartInfo.ProductOrderList.Single(x => x.ProductId.Equals(productId));
            var result = cartInfo.ProductOrderList.Remove(pItem);
            if (!cartInfo.ProductOrderList.Any())
            {
                Session[SessionConfig.SessionCartInfor] = null;
                return Json(false, JsonRequestBehavior.AllowGet);
            }

            // caculate total money
            decimal totalMoney = 0;
            foreach (var item in cartInfo.ProductOrderList)
            {
                if (item.PromotionPrice > 0)
                {
                    totalMoney += item.PromotionPrice * item.ProductQuantity;
                }
                else
                {
                    totalMoney += item.RootPriceProduct * item.ProductQuantity;
                }
            }
            cartInfo.TotalMoney = totalMoney;

            Session[SessionConfig.SessionCartInfor] = cartInfo;
            return Json(totalMoney.ToString("#,###"), JsonRequestBehavior.AllowGet);
        }

        public ActionResult CheckCart()
        {
            return View();
        }

        public ActionResult OrderInformation()
        {
            if (Session[SessionConfig.SessionCartInfor] == null)
            {
                return RedirectToAction("Index", "Home");
            }
            ViewBag.OrderId = ((OrderInfo)Session[SessionConfig.SessionCartInfor]).OrderId;
            Session[SessionConfig.SessionCartInfor] = null;
            return View();
        }

        [CheckSessionCart]
        public ActionResult ShoppingCart()
        {
            var model = (OrderInfo)Session[SessionConfig.SessionCartInfor];
            return PartialView(model);
        }

        [CheckSessionCart]
        public ActionResult ChangeProductQuantity(string productId, string quantity, string orderQuantity)
        {
            var model = (OrderInfo)Session[SessionConfig.SessionCartInfor];
         
                model.ProductOrderList.Single(m => m.ProductId == productId).ProductQuantity = int.Parse(quantity);
           
            var product = model.ProductOrderList.Single(m => m.ProductId == productId);
            model = FunctionHelpers.CalTotalOrder(model, null);
            Session[SessionConfig.SessionCartInfor] = model;

            string totalMoney = model.TotalMoney.ToString("#,###");
            return Json(totalMoney, JsonRequestBehavior.AllowGet);
        }
    }
}
